#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>

union semun
{
    int val;
};

int main(int argc, const char *argv[]) {
    key_t key;
    key = ftok("/", 'a');
    int semid;
    semid = semget(key, 3, IPC_CREAT | IPC_EXCL | 0664);
    if(semid == -1) {
        if(errno == EEXIST) {
            printf("信号灯集已经存在\n");
            semid = semget(key, 3, 0664);
        } else {
        
            perror("semget");
        }
    } else {
        printf("信号灯集创建成功");
    }

    union semun mysem;
    mysem.val = 100;
    semctl(semid, 2, SETVAL, &mysem);


    printf("2号信号灯值：%d\n", semctl(semid, 2, GETVAL));
    printf("1号信号灯值：%d\n", semctl(semid, 1, GETVAL));
    printf("0号信号灯值：%d\n", semctl(semid, 0, GETVAL));

    struct sembuf yousem;
    yousem.sem_num = 2;
    yousem.sem_op = -10;
    yousem.sem_flg = 0;
    if(semop(semid, &yousem, 1) == -1) {
        perror("semop\n");
        return -1;
    }
    printf("2号信号灯值：%d\n", semctl(semid, 2, GETVAL));
    return 0;
}
